package cn.yx.common.security.webflux.controller;

import cn.yx.common.core.constant.NumberConstant;
import cn.yx.common.core.enums.ResponseCodeEnum;
import cn.yx.common.core.pojo.ResponseVo;
import cn.yx.common.security.pojo.JwtUserDetails;
import cn.yx.common.security.service.JwtTokenService;
import cn.yx.common.security.service.SecurityCodeService;
import cn.yx.common.security.util.SecurityUtil;
import cn.yx.common.security.webflux.constant.message.AuthControllerMessageKey;
import cn.yx.common.security.webflux.vo.in.PhoneInVo;
import cn.yx.common.security.webflux.vo.in.PhoneSmsCodeInVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

/**
 * <p>用户认证控制器</p>
 *
 * @author Wgssmart
 */
@RestController
@RequestMapping("/auth")
@Api(tags = "用户认证处理")
public class AuthController {

    private final JwtTokenService jwtTokenService;

    private final SecurityCodeService securityCodeService;

    public AuthController(JwtTokenService jwtTokenService, SecurityCodeService securityCodeService) {
        this.jwtTokenService = jwtTokenService;
        this.securityCodeService = securityCodeService;
    }

    @PostMapping("login-sms-code")
    @ApiOperation(value = "获取手机登录验证码")
    public Mono<ResponseVo<String>> loginSmsCode(@RequestBody @Validated PhoneInVo phoneInVo) {
        String smsCode = securityCodeService.loginSmsCode(phoneInVo.getPhone());
        return Mono.just(ResponseVo.ok(ResponseCodeEnum.OK.getMessage(), smsCode));
    }

    @PostMapping("login/sms-code")
    @ApiOperation(value = "手机验证码登录")
    public Mono<ResponseVo<String>> phoneLogin(@RequestBody @Validated PhoneSmsCodeInVo phoneSmsCodeInVo) {
        return Mono.just(ResponseVo.ok(AuthControllerMessageKey.LOGIN_SUCCESS));
    }

    @GetMapping("require")
    @ApiOperation(value = "用户未认证")
    public Mono<ResponseVo<Void>> authRequire() {
        return Mono.just(ResponseVo.authenticationError());
    }

    @PostMapping("logout")
    @ApiOperation(value = "退出登录")
    public Mono<ResponseVo<String>> logout() {
        JwtUserDetails jwtUserDetails = SecurityUtil.currentUserDetails();
        if (jwtUserDetails.getId() == NumberConstant.LONG_ZERO) {
            return Mono.just(ResponseVo.ok(AuthControllerMessageKey.NO_NEED_TO_LOGOUT));
        }
        jwtTokenService.removeToken(jwtUserDetails);
        return Mono.just(ResponseVo.ok(AuthControllerMessageKey.LOGOUT_SUCCESS));
    }

}
